package com.hujf.mapreduce.outputformat;

import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import java.io.IOException;

/**
 * @author Hujf
 * @title: LogRecordWriter
 * @date 2021/4/110:13
 * @description: TODO
 */
public class LogRecordWriter extends RecordWriter<Text, NullWritable> {
    private FSDataOutputStream hujf;
    private FSDataOutputStream other;

    //创建2条流
    public LogRecordWriter(TaskAttemptContext job) {
        try {
            FileSystem fileSystem = FileSystem.get(job.getConfiguration());
            hujf = fileSystem.create(new Path("F:\\hbase\\data\\output24\\hujf.log"));
            other = fileSystem.create(new Path("F:\\hbase\\data\\output25\\other.log"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void write(Text key, NullWritable value) throws IOException, InterruptedException {
        String log = key.toString();
        if (log.contains("hujf")) {
            hujf.writeBytes(log+"\n");
        } else {
            other.writeBytes(log+"\n");
        }
    }

    @Override
    public void close(TaskAttemptContext context) throws IOException, InterruptedException {
        //关闭
        IOUtils.closeStream(hujf);
        IOUtils.closeStream(other);
    }
}
